import 'package:flutter/material.dart';

///@author aidenquan
/// Created by junlintianxia on 2021/6/17.

class PageLearn extends StatefulWidget {
  @override
  _PageLearnState createState() => _PageLearnState();
}

final _navigatorKey = GlobalKey<NavigatorState>();

class _PageLearnState extends State<PageLearn> {

  static int _counter = 15;

  // Initial Route: /category/5/item/15
  final pages = [
    CustomPage(
      key: ValueKey('/'),
      name: '/',
      builder: (context) => HomeScreen(),
    ),
    CustomPage(
      key: ValueKey('/category/5'),
      name: '/category/5',
      builder: (context) => CategoryScreen(id: 5),
    ),
    CustomPage(
      key: ValueKey('/item/15'),
      name: '/item/15',
      builder: (context) => ItemScreen(id: 15),
    ),
  ];

  void addPage(CustomPage page) {
    setState(() => pages.add(page));
  }

  bool _onPopPage(Route<dynamic> route, dynamic result) {
    setState(() => pages.remove(route.settings));
    return route.didPop(result);
  }

  @override
  Widget build(BuildContext context) {
    print('build: $pages');
    return MaterialApp(
      theme: ThemeData.dark(),
      home: Scaffold(
        body: PopScope(
          canPop: _navigatorKey.currentState?.canPop() ?? false,
          onPopInvokedWithResult: (didPop, result) async {
            if (_navigatorKey.currentState == null) {
              return;
            }
            if (!didPop && await _navigatorKey.currentState!.maybePop()) {
              // Handle the pop action if needed
            }
          },
          child: Navigator(
            key: _navigatorKey,
            onPopPage: _onPopPage,
            pages: List.of(pages),
          ),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            setState(() {
              final int id = ++_counter;
              pages.add(
                CustomPage(
                  key: ValueKey('/item/$id'),
                  name: '/item/$id',
                  builder: (context) => ItemScreen(id: id),
                ),
              );
            });
          },
          child: Icon(Icons.add),
        ),
      ),
    );
  }
}

class CustomPage<T> extends Page<T> {
  final WidgetBuilder builder;

  const CustomPage({
    required LocalKey? key,
    required String name,
    required this.builder
  }) : super(key: key, name: name);

  @override
  Route<T> createRoute(BuildContext context) {
    return MaterialPageRoute(settings: this, builder: builder);
  }

  @override
  String toString() {
    return '$name';
  }

}

class HomeScreen extends StatelessWidget {
  const HomeScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.red,
      child: Center(
        child: Text(
          'Home',
          style: Theme.of(context).textTheme.headlineLarge,
        ),
      ),
    );
  }
}

class CategoryScreen extends StatelessWidget {
  const CategoryScreen({super.key, required this.id});

  final int id;

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.green,
      child: Center(
        child: Text(
          'Category $id',
          style: Theme.of(context).textTheme.headlineLarge,
        ),
      ),
    );
  }
}

class ItemScreen extends StatelessWidget {
  const ItemScreen({super.key, required this.id});

  final int id;

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.blue,
      child: Center(
        child: Text(
          'Item $id\n${ModalRoute.of(context)?.settings ?? ''}',
          style: Theme.of(context).textTheme.headlineMedium,
          textAlign: TextAlign.center,
        ),
      ),
    );
  }
}
